package org.esk.dablog.modules;

import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspException;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Iterator;

/**
 * This class implements "module:init" JSP tag
 * User: esk
 * Date: 11.12.2006
 * Time: 17:09:12
 * $Id:$
 */
public class ModuleInitializationTag extends TagSupport {
    private String name;
    private String prefix;

    /**
     * processes module initialization routine
     * @return
     * @throws JspException
     */
    public int doStartTag() throws JspException {
        HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();

        WebApplicationContext context = RequestContextUtils.getWebApplicationContext(req);
        Map beans = context.getBeansOfType(ModuleFactory.class);
        if(beans == null) {
            throw new JspException("No beans of class " + ModuleFactory.class.getName() +
                    " is defined in web application context.");
        }
        for(Iterator r = beans.values().iterator(); r.hasNext(); ){
            ModuleFactory mf = (ModuleFactory) r.next();
            mf.initModule(name, prefix, req);
        }
        return super.doStartTag();
    }


    public void setName(String name) {
        this.name = name;
    }


    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
}
